package huawei

import (
	"errors"
	"time"

	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
	ces "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ces/v1"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ces/v1/model"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ces/v1/region"
)

var (
	auth      basic.Credentials
	clientMap = make(map[string]*ces.CesClient) // key:regionId

	//errors
	errRespEmpty = errors.New("the request returns as empty")
)

func Init(ak, sk string) {
	auth = basic.NewCredentialsBuilder().
		WithAk(ak).
		WithSk(sk).
		Build()
}

func crateClient(regionId string) *ces.CesClient {
	client := ces.NewCesClient(
		ces.CesClientBuilder().
			WithRegion(region.ValueOf(regionId)).
			WithCredential(auth).
			Build())
	clientMap[regionId] = client
	return client
}

//TODO 调整批量更新
func getValue(regionId, namespace, metricName, dimensionName, value string, UpdateTime time.Time) (float64, int64, error) {
	request := &model.BatchListMetricDataRequest{}
	var listDimensionsMetrics = []model.MetricsDimension{
		{
			Name:  dimensionName, //指标名ID
			Value: value,         //ID
		},
	}
	var listMetricsbody = []model.MetricInfo{
		{
			Namespace:  namespace,
			MetricName: metricName,
			Dimensions: listDimensionsMetrics,
		},
	}
	//TODO
	//now := time.Now()
	//from := now.Add(time.Minute * -2)
	to_timestamp := time.Now()
	from_timestamp := to_timestamp.Add(time.Minute * -2)
	request.Body = &model.BatchListMetricDataRequestBody{
		To:      int64(to_timestamp.UnixMilli()),
		From:    int64(from_timestamp.UnixMilli()),
		Filter:  "max",
		Period:  "1",
		Metrics: listMetricsbody,
	}
	_, found := clientMap[regionId]
	if !found {
		crateClient(regionId)
	}
	response, err := clientMap[regionId].BatchListMetricData(request)
	if err != nil {
		return 0, 0, err
	}

	//TODO 错误处理
	//TODO 空值处理
	resp := *response.Metrics
	if len(resp) == 0 {
		return 0, 0, errRespEmpty
	}
	if len(resp[0].Datapoints) == 0 {
		return 0, 0, errRespEmpty
	}
	return *resp[0].Datapoints[0].Max, resp[0].Datapoints[0].Timestamp, nil
}

func getValues(regionId, namespace, metricName, dimensionName string, values []string, UpdateTime time.Time) ([]model.BatchMetricData, error) {
	if len(values) < 1 {
		return nil, errRespEmpty
	}
	listMetricsbody := make([]model.MetricInfo, 0, len(values))
	request := &model.BatchListMetricDataRequest{}
	for _, value := range values {
		if len(value) == 0 {
			continue
		}
		var listDimensionsMetrics = []model.MetricsDimension{
			{
				Name:  dimensionName, //指标名ID
				Value: value,         //ID
			},
		}
		tmp := model.MetricInfo{
			Namespace:  namespace,
			MetricName: metricName,
			Dimensions: listDimensionsMetrics,
		}
		listMetricsbody = append(listMetricsbody, tmp)
	}

	//TODO
	//now := time.Now()
	//from := now.Add(time.Minute * -2)
	to_timestamp := time.Now()
	from_timestamp := to_timestamp.Add(time.Minute * -2)
	request.Body = &model.BatchListMetricDataRequestBody{
		To:      int64(to_timestamp.UnixMilli()),
		From:    int64(from_timestamp.UnixMilli()),
		Filter:  "max",
		Period:  "1",
		Metrics: listMetricsbody,
	}
	_, found := clientMap[regionId]
	if !found {
		crateClient(regionId)
	}
	response, err := clientMap[regionId].BatchListMetricData(request)
	if err != nil {
		return nil, err
	}

	//TODO 错误处理
	//TODO 空值处理
	return *response.Metrics, nil
}
